package com.csust.cg.mongodb.service.impl;

import com.csust.cg.mongodb.domain.Result;
import com.csust.cg.mongodb.domain.entity.ConnectGroup;
import com.csust.cg.mongodb.mapper.ConnectGroupMapper;
import com.csust.cg.mongodb.mapper.ConnectMapper;
import com.csust.cg.mongodb.service.ConnectGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author chenguang
 */
@Service
public class ConnectGroupServiceImpl implements ConnectGroupService {

    @Autowired
    private ConnectGroupMapper connectGroupMapper;

    @Autowired
    private ConnectMapper saveConnectMapper;

    @Override
    public Result getAllGroup(String userId) {
        List<ConnectGroup> groups;
        try {
            groups = connectGroupMapper.selectGroupListByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请联系开发人员！");
        }
        if (groups == null || groups.size() < 1) {
            return Result.success();
        }
        return Result.success(groups);
    }

    @Override
    public Result addGroup(String userId, String name) {
        ConnectGroup group = new ConnectGroup();
        group.setUserId(userId);
        group.setGroupName(name);
        group.setCreateTime(new Date());
        try {
            connectGroupMapper.insertGroup(group);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请联系开发人员！");
        }
        if (group.getId() != null) {
            return Result.success();
        } else {
            return Result.error("系统创建分组出错！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result removeGroup(Integer id) {
        Integer groupLine;
        try {
            groupLine = connectGroupMapper.deleteGroupById(id);
            saveConnectMapper.deleteByGroupId(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请联系开发人员！");
        }
        if (groupLine > 0) {
            return Result.success();
        } else {
            return Result.error("系统删除分组出错！");
        }
    }

    @Override
    public Result editGroup(Integer id, String name) {
        Integer line;
        ConnectGroup group = new ConnectGroup();
        group.setId(id);
        group.setGroupName(name);
        try {
            line = connectGroupMapper.updateGroupById(group);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请联系开发人员！");
        }
        if (line > 0) {
            return Result.success();
        } else {
            return Result.error("系统更新分组出错！");
        }
    }
}
